package com.xiashitech.agent.instrumentation.spring.security.inst;

import com.xiashitech.agent.cache.status.CacheStatus;
import com.xiashitech.agent.config.StartConfig;
import com.xiashitech.agent.dto.UserRequest;
import com.xiashitech.agent.instrumentation.bridge.Java8Bridge;
import com.xiashitech.agent.instrumentation.helper.calldepth.XSSpringSecurityCallDepth;
import com.xiashitech.agent.instrumentation.utils.BaggageUtil;
import com.xiashitech.agent.utils.DurationPrinter;
import io.opentelemetry.javaagent.bootstrap.CallDepth;
import io.opentelemetry.javaagent.extension.instrumentation.TypeInstrumentation;
import io.opentelemetry.javaagent.extension.instrumentation.TypeTransformer;
import io.opentelemetry.javaagent.shaded.io.opentelemetry.context.Context;
import io.opentelemetry.javaagent.shaded.io.opentelemetry.context.Scope;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.matcher.ElementMatcher;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.server.WebFilterExchange;

import java.util.Optional;

import static net.bytebuddy.matcher.ElementMatchers.*;
import static net.bytebuddy.matcher.ElementMatchers.named;
import static io.opentelemetry.javaagent.bootstrap.Java8BytecodeBridge.currentContext;
import static com.xiashitech.agent.instrumentation.spring.security.XSSpringSecuritySingletons.instrumenter;

public class XSSpringSecurityInstrumentation implements TypeInstrumentation {
    @Override
    public ElementMatcher<TypeDescription> typeMatcher() {
        return named("org.springframework.security.web.server.authentication.AuthenticationWebFilter");
    }

    @Override
    public void transform(TypeTransformer transformer) {
        transformer.applyAdviceToMethod(
                isMethod()
                        .and(isProtected())
                        .and(named("onAuthenticationSuccess"))
                        .and(takesArgument(0, named("org.springframework.security.core.Authentication")))
                        .and(takesArgument(1, named("org.springframework.security.web.server.WebFilterExchange"))),
                XSSpringSecurityInstrumentation.class.getName() + "$AuthenticateAdvice");
    }
    public static class AuthenticateAdvice {

        @Advice.OnMethodEnter(suppress = Throwable.class)
        public static void onEnter(
                @Advice.Argument(0) Authentication authentication,
                @Advice.Argument(1) WebFilterExchange webFilterExchange,
                @Advice.Local("otelUser") UserRequest userRequest,
                @Advice.Local("otelCallDepth") CallDepth callDepth,
                @Advice.Local("otelContext") Context context,
                @Advice.Local("otelScope") Scope scope) {
            DurationPrinter durationPrinter = new DurationPrinter("XSSpringSecurityInstrumentation");
            if(CacheStatus.cannotRun()) {
                return;
            }
            callDepth = CallDepth.forClass(XSSpringSecurityCallDepth.class);
            if (callDepth.getAndIncrement() > 0) {
                return;
            }
            try {
                Optional<UserRequest> userRequestOptional = Java8Bridge.executeRuleForUserInfoMatchRule(authentication);
                if(userRequestOptional.isPresent()) {
                    userRequest = userRequestOptional.get();
                } else {
                    userRequest = UserRequest.builder().build();
                }
                userRequest.setWebFilterExchange(webFilterExchange);
                Context parentContext = currentContext();
                if (instrumenter().shouldStart(parentContext,userRequest)) {
                    parentContext = BaggageUtil.syncBaggage().build().storeInContext(parentContext);
                    context = instrumenter().start(parentContext, userRequest);
                    context = BaggageUtil.syncBaggage().build().storeInContext(context);
                    scope = context.makeCurrent();
                }
            } catch (Throwable e) {
                StartConfig.throwableStackPrinter(e);
            }
            durationPrinter.printElapseDuration("XSResultLineAdvice b");
        }

        @Advice.OnMethodExit(onThrowable = Throwable.class, suppress = Throwable.class)
        public static void onExit(
                @Advice.Argument(0) Authentication authentication,
                @Advice.Argument(1) WebFilterExchange webFilterExchange,
                @Advice.Return Object objReturn,
                @Advice.Local("otelUser") UserRequest userRequest,
                @Advice.Local("otelCallDepth") CallDepth callDepth,
                @Advice.Local("otelContext") Context context,
                @Advice.Local("otelScope") Scope scope) {
            DurationPrinter durationPrinter = new DurationPrinter("XSSpringSecurityInstrumentation");
            if(CacheStatus.cannotRun()) {
                return;
            }
            if (callDepth.decrementAndGet() > 0) {
                return;
            }
            if (scope == null) {
                return;
            }
            scope.close();
            instrumenter().end(context,userRequest,objReturn,null);
            durationPrinter.printElapseDuration("AuthenticateAdvice e");
        }
    }
}
